<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" inline v-show="showSearch">
          <el-form-item label="班级名称" prop="className">
            <el-input
              v-model="queryParams.className"
              placeholder="请输入班级名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="table-tools mb8">
          <div>
            <el-button
              v-if="!isStudent"
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              >新增</el-button
            >
            <el-button
              type="success"
              plain
              v-if="!isStudent"
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              >修改</el-button
            >
            <el-button
              type="danger"
              plain
              v-if="!isStudent"
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              >删除</el-button
            >
            <!-- <el-button type="info" plain icon="Upload" @click="handleImport"
              >导入</el-button
            >
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              >导出</el-button
            > -->
          </div>
          <div>
            <right-toolbar
              v-model:showSearch="showSearch"
              @queryTable="getList"
            />
          </div>
        </div>

        <el-table
          v-loading="loading"
          :data="classList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="班级名称"
            align="center"
            key="className"
            prop="className"
            show-overflow-tooltip
          />
          <el-table-column
            label="班级描述"
            align="center"
            key="classCode"
            prop="classCode"
            show-overflow-tooltip
          />
          <template v-if="isStudent">
            <el-table-column
              label="状态"
              align="center"
              key="exist"
              prop="exist"
              width="120"
            >
              <template #default="scope">
                <span>{{ scope.row.exist ? "已加入" : "未加入" }}</span>
              </template>
            </el-table-column>
          </template>

          <el-table-column
            label="班级人数"
            align="center"
            key="stuCount"
            prop="stuCount"
            width="120"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="creatTime"
            width="160"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.creatTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                type="primary"
                link
                icon="Edit"
                v-if="!isStudent"
                @click="handleUpdate(scope.row)"
                >修改
              </el-button>
              <el-button
                type="primary"
                link
                icon="Delete"
                v-if="!isStudent"
                @click="handleDelete(scope.row)"
                >删除
              </el-button>
              <el-button
                type="primary"
                link
                icon="plus"
                @click="handleJoin(scope.row)"
                v-if="isStudent"
                >加入班级
              </el-button>
              <template v-else>
                <el-button
                  type="primary"
                  link
                  icon="plus"
                  @click="handleAddStu('add', scope.row)"
                  >添加学生
                </el-button>
                <el-button
                  type="primary"
                  link
                  icon="delete"
                  @click="handleAddStu('del', scope.row)"
                  >删除学生
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改班级配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="班级名称" prop="className">
              <el-input v-model="form.className" placeholder="请输入班级名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="班级描述" prop="classCode">
              <el-input v-model="form.classCode" placeholder="请输入班级描述" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加学生对话框 -->
    <el-dialog
      :title="stuTitle"
      v-model="addStudentOpen"
      v-if="addStudentOpen"
      width="600px"
      append-to-body
    >
      <el-table
        v-loading="loading"
        :data="studentList"
        @selection-change="handleStudentChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          label="编号"
          align="center"
          key="userId"
          prop="userId"
        />
        <el-table-column
          label="姓名"
          align="center"
          key="nickName"
          prop="nickName"
          show-overflow-tooltip
        />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="selectStudentConfirm"
            >确 定</el-button
          >
          <el-button @click="selectStudentCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Class">
import {
  getSchoolClassList,
  deleteClassByIds,
  addSchoolClass,
  editSchoolClass,
  getClassStuList,
  addClassStudent,
  delClassStudent,
  getStuByClass,
} from "@/api/core/class";
import {
  getCurrentInstance,
  reactive,
  ref,
  toRefs,
  watch,
  computed,
} from "vue";
import { parseTime } from "@/utils/ruoyi";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();

const classList = ref([]);
const studentList = ref([]);
const open = ref(false);
const addStudentOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const studentSelect = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const stuFlag = ref("");
const userStore = useUserStore();
const stuTitle = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    className: undefined,
    classCode: undefined,
  },
  currentRow: {},
  rules: {
    className: [
      { required: true, trigger: "blur", message: "班级名称不能为空" },
    ],
  },
});
const isStudent = computed(() => useUserStore().isStudent);
console.log("isStudent", useUserStore());
const { queryParams, form, rules, currentRow } = toRefs(data);

/** 查询班级列表 */
function getList() {
  loading.value = true;
  getSchoolClassList(
    proxy.addDateRange(queryParams.value, dateRange.value)
  ).then((res) => {
    loading.value = false;
    classList.value = res.rows;
    total.value = res.total;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const classIds = row.id || ids.value.toString();
  proxy.$modal
    .confirm('是否确认删除班级编号为"' + classIds + '"的数据项？')
    .then(function () {
      return deleteClassByIds(classIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
function handleStudentChange(selection) {
  studentSelect.value = selection.map((item) => item.userId);
}

/** 重置操作表单 */
function reset() {
  form.value = {
    id: null,
    className: "",
    classCode: "",
  };
  proxy.resetForm("userRef");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 加入班级按钮操作 */
function handleJoin(row) {
  console.log("row", row);
  proxy.$modal
    .confirm('是否加入班级名称为"' + row.className)
    .then(() => {
      addClassStudent({
        stuId: userStore.userId,
        classId: row.id,
      }).then((res) => {
        proxy.$modal.msgSuccess("加入成功");
        getList();
      });
    })
    .catch(() => {});
  // return;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加班级";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value.id = row.id;
  form.value.className = row.className;
  form.value.classCode = row.classCode;
  open.value = true;
  title.value = "修改班级";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      if (form.value.id) {
        editSchoolClass(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSchoolClass(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
function handleAddStu(type, row) {
  stuFlag.value = type;
  currentRow.value = row;
  studentSelect.value = [];
  addStudentOpen.value = true;
  let param;
  if (type == "del") {
    param = {
      classId: row.id,
    };
    stuTitle.value = "删除学生";
    getStuByClass(param).then((res) => {
      studentList.value = res.rows;
    });
  } else {
    stuTitle.value = "添加学生";
    getClassStuList({
      classId: row.id,
    }).then((res) => {
      console.log("res", res);
      // 过滤出不在班级的学生
      studentList.value = res.rows.filter((item) => !item.exist);
    });
  }
}
/**选择学生确认**/
function selectStudentConfirm() {
  if (studentSelect.value.length > 0) {
    if (stuFlag.value == "add") {
      let param = studentSelect.value.map((item) => {
        return {
          stuId: item,
          classId: currentRow.value.id,
        };
      });
      addClassStudent(param).then((res) => {
        proxy.$modal.msgSuccess("添加成功");
        getList();
      });
    } else {
      delClassStudent({
        stuId: studentSelect.value.toString(),
        classId: currentRow.value.id,
      }).then((res) => {
        proxy.$modal.msgSuccess("删除成功");
        getList();
      });
    }

    addStudentOpen.value = false;
  } else {
    proxy.$modal.msgWarning("请选择一条数据");
  }
}
/** 取消按钮 */
function selectStudentCancel() {
  addStudentOpen.value = false;
}

getList();
</script>

<style scoped lang="scss"></style>
